<template>
  <div class="app-container">
    <el-row type="flex" align="middle">
      <h3 style="margin-left:20px">提现账号设置</h3>
      <el-tooltip placement="top-start">
        <div style="font-size:14px;line-height:18px" slot="content">
          绑定账号：当初注册家巴啦绑定的微信和手机号
          <br />更换账号：绑定的账号，需要进行解绑才能更换绑定新的账号
        </div>
        <p style="margin-left:10px;font-size:14px;color:rgb(145, 145, 145)">
          帮助
          <i class="el-icon-info"></i>
        </p>
      </el-tooltip>
    </el-row>
    <div style="width:500px">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="accountHolderName">
          <el-input
            v-model="ruleForm.accountHolderName"
            :disabled="true"
            placeholder="请点击微信绑定扫码自动获取"
          ></el-input>
        </el-form-item>
        <el-form-item label="微信账号" required>
          <svg-icon icon-class="微信" v-if="userWxBind" />
          <span v-if="userWxBind" class="text" style="margin-left:10px" @click="wxOutBind">解绑</span>
          <span v-else class="text" @click="handleWxBind">微信绑定</span>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" :disabled="userWxBind" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="验证码" v-if="wxUserInfo.unionid&&!userWxBind" prop="code">
          <el-row type="flex">
            <el-input
              style="width:180px;margin-right:10px"
              v-model="ruleForm.code"
              placeholder="请填写您的验证码"
            ></el-input>
            <el-button v-if="timer===60" type="primary" @click="handleCode">获取验证码</el-button>
            <el-button v-else type="primary" :disabled="true">已发送({{timer}})</el-button>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" v-if="wxUserInfo.unionid&&!userWxBind">
            <el-button type="primary" @click="handleClickBind">绑定</el-button>
          </el-row>
        </el-form-item>

        <el-form-item label="验证码" v-if="userWxBind&&isUserBind" prop="code">
          <el-row type="flex">
            <el-input
              style="width:180px;margin-right:10px"
              v-model="ruleForm.code"
              placeholder="请填写您的验证码"
            ></el-input>
            <el-button v-if="timer===60" type="primary" @click="handleCode">获取验证码</el-button>
            <el-button v-else type="primary" :disabled="true">已发送({{timer}})</el-button>
          </el-row>
        </el-form-item>
        <el-form-item v-if="userWxBind&&isUserBind">
          <el-row type="flex">
            <el-button type="primary" @click="handleClickDeleteBind">解绑</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <!-- 微信绑定 -->
    <el-dialog
      title="微信扫码"
      :visible.sync="wxBindDialog"
      width="700px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @open="openWxCodeUrl"
      @close="wxCode=''"
    >
      <div class="shadow-title"></div>
      <div id="login_container" style="width:100%;text-align:center">
        <iframe
          ref="iframeRef"
          class="code-iframe"
          scrolling="no"
          sandbox="allow-scripts allow-top-navigation"
          :src="wxCode"
        ></iframe>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="wxBindDialog=false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { veryCode } from '@/api/common'
import {
  sendCode,
  getRedirectUrl,
  selectUserInfoByUnionId,
  getOpenIdByUnionId
} from '@/api/user'
import {
  getByBusinessAndType,
  deleteByBusinessAndType,
  capitalAccount,
  getByUnionIdAndBusiness
} from '@/api/mechanism'

export default {
  name: 'Withdrawal',
  inject: ['reload'],
  data() {
    return {
      isUserBind: false, // 绑定微信用户是否匹配
      userWxBind: false, // 是否绑定微信
      wxBindDialog: false,
      wxCode: '',
      timer: 60,
      openid: '',
      ruleForm: {
        accountHolderName: '',
        nickname: '',
        phone: '',
        code: ''
      },
      rules: {
        phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['businessId', 'name', 'userInfo', 'wxUserInfo'])
  },
  created() {
    getByBusinessAndType({
      businessId: this.businessId,
      type: 1
    }).then((res) => {
      if (!res.data) {
        this.userWxBind = false
      } else {
        this.userWxBind = true
        this.wxUserInfo.unionid && this.veryUserInfo()
        this.ruleForm = res.data
        this.ruleForm.accountHolderName = this.wxUserInfo.nickname
      }
    })
    this.wxUserInfo.openid && this.getOpenid()
    // this.wxUserInfo.openid && this.getWxbind()
    // // 已绑定时检验是否绑定用户
    // if (this.wxUserInfo.unionid && this.userWxBind) {
    //   this.veryUserInfo()
    // }
  },
  watch: {
    $route(to, form) {
      // console.log(to, form, "to,form");
    }
  },
  methods: {
    wxOutBind() {
      this.wxBindDialog = true
      // deleteByBusinessAndType({
      //   unionId: this.userInfo.wxId,
      //   businessId: this.businessId,
      // }).then((res) => {
      //   this.$message.success("解绑成功");
      // });
    },

    handleWxBind() {
      this.wxBindDialog = true
    },
    // 解绑
    handleClickDeleteBind() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          veryCode({
            phone: this.ruleForm.phone,
            code: this.ruleForm.code
          }).then((res) => {
            deleteByBusinessAndType({
              unionId: this.wxUserInfo.unionid,
              businessId: this.businessId
            }).then((res) => {
              this.$message.success('解绑成功')
              this.isUserBind = false
              this.userWxBind = false
              this.$refs.ruleForm.resetFields()
              this.$router.replace({
                path: '/redirect/system/withdrawal'
              })
            })
          })
        } else {
          return false
        }
      })
    },
    // 绑定
    handleClickBind() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          veryCode({
            phone: this.ruleForm.phone,
            code: this.ruleForm.code
          }).then((res) => {
            capitalAccount({
              businessId: this.businessId,
              businessName: this.name,
              type: 1,
              phone: this.ruleForm.phone,
              accountNo: this.openid,
              accountName: this.wxUserInfo.nickname,
              accountHolderName: this.wxUserInfo.nickname,
              unionId: this.wxUserInfo.unionid
            }).then((user) => {
              this.$message({
                message: '绑定成功',
                type: 'success'
              })
              this.userWxBind = true
              this.$router.replace({
                path: '/redirect/system/withdrawal'
              })
            })
          })
        } else {
          return false
        }
      })
    },
    // // 需要绑定时获取真实姓名手机号码
    // async getWxbind() {
    //   const userInfo = await selectUserInfoByUnionId({
    //     unionId: this.wxUserInfo.unionid
    //   })
    //   if (userInfo.data.realName) {
    //     this.ruleForm.accountHolderName = userInfo.data.realName
    //   } else {
    //     this.$message({
    //       message: '请先在手机端认证',
    //       type: 'error'
    //     })
    //   }
    // },
    // 解绑验证用户身份
    veryUserInfo() {
      getByUnionIdAndBusiness({
        unionId: this.wxUserInfo.unionid,
        businessId: this.businessId
      }).then((res) => {
        if (res.data) {
          this.isUserBind = true
        } else {
          this.$message({
            message: '非绑定用户无权解绑',
            type: 'error'
          })
          this.isUserBind = false
        }
      })
    },
    handleCode() {
      this.$refs.ruleForm.validateField('phone', (err) => {
        if (err) {
          return false
        } else {
          this.timer = 59
          const time = setInterval(() => {
            this.timer--
            if (this.timer <= 0) {
              clearInterval(time)
              this.timer = 60
            }
          }, 1000)
          sendCode({ phone: this.ruleForm.phone }).then((res) => {
            this.$message.success('验证码发送成功')
          })
        }
      })
    },
    // 获取openid
    getOpenid() {
      getOpenIdByUnionId({
        unionId: this.wxUserInfo.unionid
      }).then((res) => {
        this.openid = res.data
      })
    },
    openWxCodeUrl() {
      getRedirectUrl().then((res) => {
        this.wxCode = `${res.data}&self_redirect=false`
      })
      // this.$nextTick(() => {
      //   var obj = new WxLogin({
      //     self_redirect: false,
      //     id: 'login_container',
      //     appid: 'wxe911e0190045a775',
      //     scope: 'snsapi_login',
      //     redirect_uri: 'https%3A%2F%2Fapp.jiabala.com%2F%23%2FwxBind',
      //     state: Math.ceil(Math.random() * 1000),
      //     href: 'data:text/css;base64,QGNoYXJzZXQgIlVURi04IjsKLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30K',
      //     success: function(res) {
      //       console.log(res, '3333333333')
      //     }
      //   })
      //   console.log(obj, ',,,,,,,,')
      // })
    }
  },
  // 离开当前页面后执行
  destroyed: function() {
    this.$store.dispatch('user/removewxUserInfo')
  }
}
</script>
<style lang="scss" scoped>
.text {
  cursor: pointer;
  color: red;
}
.shadow-title {
  position: absolute;
  top: 70px;
  width: 80%;
  height: 50px;
  background: #fff;
  // border: 1PX solid #CCCC;
}
.code-iframe {
  width: 300px;
  height: 400px;
  border: none;
  overflow-y: hidden;
  /deep/.impowerBox .title {
    display: none;
  }
}
</style>
